import { Injectable, Query } from '@nestjs/common';
import { PrismaService } from '@/common/service/prisma/prisma.service';
import { Table } from '../dto/index'
import { request } from 'http';
@Injectable()
export class TableService {
    constructor(private prisma: PrismaService) { }

    // 列出所有的表
    async getTable() {
        const resp: any[] = await this.prisma.$queryRawUnsafe(`
            SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE();
            `)
        const result: Table[] = resp.map((e, i) => {
            return { id: i, name: e.TABLE_NAME }
        })
        const filter: Table[] = []
        const sys: string[] = [
            'front_account', 'gen_table', 'gen_table_column', 'sys_config', 'sys_dept', 'sys_dict_data', 'sys_dict_type', 'sys_logininfor', 'sys_menu', 'sys_notice', 'sys_post', 'sys_role', 'sys_role_dept', 'sys_role_menu', 'sys_user', 'sys_user_post', 'sys_user_role',
        ]
        result.forEach(element => {
            if (!sys.includes(element.name)) {
                filter.push(element)
            }
        });

        const fianlResult = filter.map((e, i) => { return { ...e, id: i + 1 } })

        return {
            rows: fianlResult,
            total: fianlResult.length
        }
    }

    // 查找表
    async findTable(name: string) {
        const resp: any[] = await this.prisma.$queryRawUnsafe(`
            SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() and table_name = '${name}';
            `)

        const result: Table[] = resp.map((e, i) => {
            return { id: i, name: e.TABLE_NAME }
        })

        return {
            data: result[0],
        }
    }
    // 更新表
    async updateTable(old: string, newone: string) {

        const resp: any = await this.prisma.$executeRawUnsafe(`
          
            RENAME   TABLE \`${old}\` TO \`${newone}\`
            `)
        // console.log(resp);

        return resp
    }

    // 添加表
    async addTable(name: string) {

        const resp: any = await this.prisma.$executeRawUnsafe(`
          CREATE TABLE \`${name}\`  (\`eng\` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,\`chi\` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,\`id\` int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (\`id\`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = DYNAMIC;`)
        // console.log(resp);

        return resp
    }

    // 添加表
    async delTable(name: string) {

        const resp: any = await this.prisma.$executeRawUnsafe(`DROP TABLE \`${name}\`;`)
        // console.log(resp);

        return resp
    }

}
